/*
 * @Author: your name
 * @Date: 2022-10-28 10:21:52
 * @LastEditTime: 2022-11-15 11:48:00
 * @LastEditors: yuhan
 * @Description:
 * @FilePath: \apiadmin\src\utils\index.js
 */

import { setting } from '@/config/setting';
import axios from '@/utils/request';
const { title } = setting;

export const getFormDataUrl = (type, baseUrl, formInfo) => {
  const api = {
    url: `${baseUrl}`,
    method: type,
    params: formInfo || '',
    // headers: {
    //   'Content-Type': `multipart/form-data`
    // },
    data: formInfo || '',
  };
  if (type === 'post') {
    delete api.params;
  }
  if (type === 'get') {
    delete api.data;
  }
  return new Promise((resolve, reject) => {
    axios(api)
      .then(({ code, result }) => {
        if (code === 200) {
          resolve(result);
        } else if (code === 500) {
          ElMessage.error(message);
          // router.push('/login');
        } else {
          resolve(data);
        }
      })
      .catch((err) => {
        reject(err?.data || err);
      });
  });
};

export const getPageTitle = (pageTitle) => {
  if (pageTitle) {
    return `${pageTitle}-${title}`;
  }
  return `${title}`;
};

/**
 * 时间戳格式转换以及计算
 * */
export function formatTime(time = 0, format = 'YYYY-MM-DD hh:mm:ss') {
  const now = new Date().getTime();

  if (!time) time = now;

  while (time.toString().length < 13) time += '0';

  const date = new Date(time);
  // 补零
  function zeroFill(val) {
    return String(val).length < 2 ? '0' + val : val;
  }
  date.getMonth();
  /** 参数集 年-月-日 时:分:秒 */
  const arg = {
    year: date.getFullYear(),
    month: zeroFill(date.getMonth() + 1),
    day: zeroFill(date.getDate()),
    hours: zeroFill(date.getHours()),
    minutes: zeroFill(date.getMinutes()),
    seconds: zeroFill(date.getSeconds()),
  };

  /** 判断有没有指定的时间格式 */
  switch (format) {
    case 'YYYY-MM-DD hh:mm:ss':
      return `${arg.year}-${arg.month}-${arg.day} ${arg.hours}:${arg.minutes}:${arg.seconds}`;
    case 'YYYY-MM-DD':
      return `${arg.year}-${arg.month}-${arg.day}`;
    case 'MM-DD':
      return `${arg.month}-${arg.day}`;
    case 'hh:mm:ss':
      return `${arg.hours}:${arg.minutes}:${arg.seconds}`;
    case 'hh:mm':
      return `${arg.hours}:${arg.minutes}`;
    case 'computed': //判断是不是需要进行计算
      if (now > time) {
        const dt = Math.abs(time - now), //时间已过去多少毫秒
          S = dt / 1000, //秒
          M = S / 60, //分
          H = M / 60, //小时
          D = H / 24, //天
          W = D / 7; //周

        /**
      ~~ ==>表示取整数部分 类似与 parseInt
    */
        if (~~W > 0 && W < 3) {
          return ~~W + '周前';
        } else if (D < 7 && ~~D > 0) {
          return ~~D + '天前';
        } else if (~~H > 0 && H < 24) {
          return ~~H + '小时前';
        } else if (~~M > 0 && M < 60) {
          return ~~M + '分钟前';
        } else if (~~S > 0 && S < 60) {
          return ~~S + '秒前';
        }
      } else {
        console.log('未来的时间');
      }
      return `${arg.year}-${arg.month}-${arg.day} ${arg.hours}:${arg.minutes}:${arg.seconds}`;
  }
}

// 转换文件流
export function blobToFile(data, name) {
  let blob = new Blob([data], {
    type: 'application/octet-stream',
  }); // 转化为blob对象
  const timestamp = new Date().getTime();
  let filename = name || `文件_${timestamp}.xlsx`; // 判断是否使用默认文件名
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(blob, filename);
  } else {
    var blobURL = window.URL.createObjectURL(blob); // 将blob对象转为一个URL
    var tempLink = document.createElement('a'); // 创建一个a标签
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', filename); // 给a标签添加下载属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink); // 将a标签添加到body当中
    tempLink.click(); // 启动下载
    document.body.removeChild(tempLink); // 下载完毕删除a标签
    window.URL.revokeObjectURL(blobURL);
  }
}

// 对象转数组 出参每个子都要求是key value组合
export function ObjToArr(obj) {
  let newArr = [];
  for (let key in obj) {
    newArr.push({
      key,
      value: obj[key],
    });
  }
  return newArr;
}

// 数组转对象 入参每个子都要求是key value组合
export function ArrToObj(arr) {
  let newObj = {};
  if (arr && arr.length > 0) {
    arr.forEach((item) => {
      newObj[item.key] = item.value;
    });
  }
  return newObj;
}
